package sparsearray;

public class SparseArray {

    public static void main(String[] args) {
        //创建一个原始的二维数组11 * 11
        //0：表示没有棋子，1表示黑子，2表示蓝子
        int[][] chessArr1 = new int[11][11];
        chessArr1[1][2] = 1;
        chessArr1[2][3] = 2;
        chessArr1[3][4] = 3;
        //输出原始的二维数组
        System.out.println("原始的二维数组");
        for (int[] row:chessArr1){
            for (int data:row){
                System.out.printf("%d\t",data);
            }
            System.out.println();
        }
        //将二维数组转成稀疏数组
        //1.先遍历二维数组得到非0的个数
        int sum = 0;
        for (int i = 0;i < chessArr1.length; i++){
            for (int j = 0;j < chessArr1.length; j++){
                if (chessArr1[i][j]!=0){
                    sum ++;
                }
            }
        }
        System.out.printf("sum=%d",sum);

        //2.创建对应的稀疏数组
        int sparseArr[][] = new int[sum+1][3];
        //给稀疏数组赋值
        sparseArr[0][0] = chessArr1.length;
        sparseArr[0][1] = chessArr1[0].length;
        sparseArr[0][2] = sum;

        //遍历二维数组，将非0的值存放稀疏数组中
        int index = 1;//用于记录第几个非0数据
        for (int i = 0;i < chessArr1.length; i++){
            for (int j = 0;j < chessArr1.length; j++){
                if (chessArr1[i][j]!=0){
                    sparseArr[index][0] = i;
                    sparseArr[index][1] = j;
                    sparseArr[index][2] = chessArr1[i][j];
                    index ++;
                }
            }
        }
        System.out.println("稀疏数组");
        for (int i = 0;i < sparseArr.length; i++){
            for (int j = 0;j < sum; j++){
                System.out.printf("%d\t",sparseArr[i][j]);
            }
            System.out.println();
        }
        int[][] chessArr2 = new int[sparseArr[0][0]][sparseArr[0][1]];
        for (int i = 0; i < sparseArr[0][2]; i++){
            chessArr2[sparseArr[i+1][0]][sparseArr[i+1][1]] = sparseArr[i+1][2];
        }

        System.out.println("转换后的的二维数组");
        for (int[] row:chessArr2){
            for (int data:row){
                System.out.printf("%d\t",data);
            }
            System.out.println();
        }
    }
}
